package com.hoshiicloud.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.GoodsSpecifications;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.goods.GoodsSpecificationsMapper;
import com.hoshiicloud.goods.service.GoodsSpecificationsService;
import com.hoshiicloud.goods.vo.GoodsSpecificationsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 商品规格 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class GoodsSpecificationsServiceImpl extends ServiceImpl<GoodsSpecificationsMapper, GoodsSpecifications> implements GoodsSpecificationsService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private GoodsSpecificationsMapper goodsSpecificationsMapper;

    @Override
    @Logable(authName = "商品管理-商品规格管理-分页查询商品规格")
    @Cacheable(cacheNames = "GoodsSpecifications", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<GoodsSpecifications> getPage(Page<GoodsSpecifications> page, Wrapper<GoodsSpecifications> queryWrapper, String key) {
        baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecifications", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品规格-查询商品规格 ")
    public GoodsSpecifications getById(Long id) {
        return baseMapper.selectById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecifications", allEntries = true)
    @Logable(authName = "商品管理-商品规格-新增商品规格")
    public boolean save(GoodsSpecifications entity) {

        // 主键ID生成
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        QueryWrapper<GoodsSpecifications> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsSpecifications::getCompanyId,entity.getCompanyId())
                .eq(GoodsSpecifications::getSpecType,entity.getSpecType())
                .eq(GoodsSpecifications::getSpecName,entity.getSpecName())
                .eq(GoodsSpecifications::getDeleted,0);

        GoodsSpecifications old = this.getOne(q);
        if( null != old){
            throw new ServiceException("该租户已存在规格类型["+entity.getSpecType()+"]的规格值分类名["+entity.getSpecName()+"]");
        }
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecifications", allEntries = true)
    @Logable(authName = "商品管理-商品规格管理-修改商品规格")
    public boolean updateById(GoodsSpecifications entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());

        QueryWrapper<GoodsSpecifications> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsSpecifications::getCompanyId,entity.getCompanyId())
                .eq(GoodsSpecifications::getSpecType,entity.getSpecType())
                .eq(GoodsSpecifications::getSpecName,entity.getSpecName())
                .eq(GoodsSpecifications::getDeleted,0)
                .ne(GoodsSpecifications::getId,entity.getId());

        GoodsSpecifications old = this.getOne(q);
        if( null != old){
            throw new ServiceException("该租户已存在规格类型["+entity.getSpecType()+"]的规格值分类名["+entity.getSpecName()+"]");
        }

        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecifications", allEntries = true)
    @Logable(authName = "商品管理-商品规格管理-删除商品规格")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        GoodsSpecifications entity = this.getById(id);
        if (null == entity) {
            log.error("删除商品规格异常，无法找到商品规格记录");
            throw new ServiceException("删除商品规格异常，无法找到商品规格记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecifications", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品规格管理-根据id集合查询商品规格")
    public List<GoodsSpecifications> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecifications", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#specId")
    @Logable(authName = "商品管理-商品规格管理-根据 规格Id 获取规格信息")
    public GoodsSpecificationsVo getSpecById(Long specId) {
        return goodsSpecificationsMapper.getSpecById(specId);
    }
}
